<?php
/**
 * @package		简易CMS
 * @subpackage	获取最新的SVN版本号
 * @version		$Id: block_sql.php 18 2012-06-07 17:29:09Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if(!defined('IN_JYCMS')) {
	exit('Access Denied');
}

require_once libfile('commonblock_html', 'block/html');

class block_sql extends commonblock_html {
	function block_sql() {}

	function name() {
		return lang('blockclass', 'blockclass_html_script_sql');
	}

	function getsetting() {
		global $_G;
		$settings = array(
			'sql' => array(
				'title' => 'SQL语句',
				'type' => 'textarea',
				'default' => 'SELECT * FROM `pre_common_category`'
			),

			'template' => array(
				'title' => 'HTML模板',
				'type' => 'textarea',
				'default' => '[node]{catname}<BR>[/node]'
			),

			'start' => array(
				'title' => '起始数据行数',
				'type' => 'text',
				'default' => 0
			),
			'limit' => array(
				'title' => '显示数据条数',
				'type' => 'text',
				'default' => 5
			)
		);
		return $settings;
	}

	function getdata($style, $parameter) {
		global $_G;
		$tablepre = $_G['config']['db']['1']['tablepre'];

		$sql = !empty($parameter['sql']) ? ($parameter['sql']) : '';
		$start = !empty($parameter['start']) ? intval($parameter['start']) : 0;
		$limit = !empty($parameter['limit']) ? intval($parameter['limit']) : 5;


		$writedata = '';
		if ($sql != '') {
			$searchs1 = $replaces1 = array();
			$searchs1[] = '{$tablepre}';
			$replaces1[] = $tablepre;
			$sql = str_replace($searchs1, $replaces1, stripslashes($sql));
			$sql = ltrim(strtolower($sql));
			$i = strpos($sql , 'select');
			if ($i != 0){
				$writedata = '只能定义SELECT语句';
				return array('html' => $writedata, 'data' => null);
			}
			$sqldata = $sql.' limit '.$start.','.$limit.';';
			$query = DB::query($sqldata);

			$writedata = '';
			$requesttemplatebody = '';
			$requesttemplate = stripslashes($parameter['template']);
			if(preg_match("/\[node\](.+?)\[\/node\]/is", $requesttemplate, $node)) {
				$requesttemplatebody = $requesttemplate;
				$requesttemplate = $node[1];
			}

			while($row = DB::fetch($query)) {
				$searchs = $replaces = array();
				foreach(array_keys($row) as $key) {
					$searchs[] = '{'.$key.'}';
					$replaces[] = htmlspecialchars($row[$key]);
					$searchs[] = '{rawurlencode('.$key.')}';
					$replaces[] = rawurlencode($row[$key]);
				}
				$writedata .= str_replace($searchs, $replaces, $requesttemplate);
			}

			if ($requesttemplatebody){
				$oldwritedata = $writedata;
				$writedata = str_replace($node[0], $oldwritedata, $requesttemplatebody);
			}
		}else{
			$writedata = '没有定义SQL';
		}
		return array('html' => $writedata, 'data' => null);
	}
}
